/*
 * fulihui.com Inc.
 * Copyright (c) 2015-2016 All Rights Reserved.
 */
package com.fulihui.information.service;

import com.fulihui.information.api.CommentsService;
import com.fulihui.information.biz.counter.ContentCommentTimesOperableCounter;
import com.fulihui.information.core.repository.CommentsRepository;
import com.fulihui.information.core.repository.ContentRepository;
import com.fulihui.information.dto.CommentsDTO;
import com.fulihui.information.dto.ContentDTO;
import com.fulihui.information.model.UserContentOperate;
import com.fulihui.information.request.CommentsFabulousRequest;
import com.fulihui.information.request.CommentsIdsRequest;
import com.fulihui.information.request.CommentsRequest;
import org.apache.dubbo.config.annotation.Service;
import org.near.servicesupport.error.Errors;
import org.near.servicesupport.result.BaseResult;
import org.near.servicesupport.result.ResultBuilder;
import org.near.servicesupport.result.TMultiResult;
import org.near.servicesupport.result.TPageResult;
import org.near.servicesupport.util.ServiceAssert;
import org.near.toolkit.common.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.near.servicesupport.result.ResultBuilder.fail;
import static org.near.servicesupport.result.ResultBuilder.succ;
import static org.springframework.util.StringUtils.isEmpty;

/**
 * @author yunfeng.li
 * @version $Id: v 0.1 2017年01月10日 10:52 yunfeng.li Exp $
 */
@Service(version = "1.0.0")
public class CommentsServiceImpl implements CommentsService {
    private final static Logger LOGGER = LoggerFactory
            .getLogger(CommentsServiceImpl.class);
    @Autowired
    private CommentsRepository commentsRepository;
    @Autowired
    private ContentRepository  contentRepository;

    /**
     * 发表/回复评论
     * @see com.fulihui.information.api.CommentsService#deliverComment(com.fulihui.information.request.CommentsRequest)
     */
    @Override
    public BaseResult deliverComment(CommentsRequest request) {
        // 调取资讯信息
        String newsId = checkNotNull(request.getNewsId());
        ContentDTO news = contentRepository.detail(newsId);
        request.setNewsDigest(news.getTitle());
        boolean result = commentsRepository.saveComment(request);

        if (result) {
            // 通知评论数加1
            ContentCommentTimesOperableCounter counter = new ContentCommentTimesOperableCounter();
            UserContentOperate operate = new UserContentOperate();
            operate.setContentId(request.getNewsId());
            counter.operate(operate);
        }
        return result ? succ() : fail(Errors.Commons.SYSTEM_ERROR);
    }

    @Override
    public TPageResult<CommentsDTO> queryPageByNewsId(CommentsRequest request) {
        ServiceAssert.notBlank(request.getNewsId(), Errors.Commons.REQUEST_PARAMETER_ERROR);
        List<CommentsDTO> commentsDTOList = commentsRepository.queryByPage(request);
        // 将该评论下的所有回复查询出来
        for (CommentsDTO comments : commentsDTOList) {
            Long discussId = comments.getId();
            List<CommentsDTO> subComments = commentsRepository.selectByDiscussId(discussId);
            comments.setSubComments(subComments);
        }
        int queryPageCount = commentsRepository.queryByCount(request);
        return ResultBuilder.succTPage(commentsDTOList, request.getPage(), request.getRows(),
                queryPageCount);
    }

    @Override
    public TMultiResult<CommentsDTO> queryPageByDiscussId(CommentsRequest request) {
        ServiceAssert.notNull(request.getDiscussId(), Errors.Commons.REQUEST_PARAMETER_ERROR);
        List<CommentsDTO> commentsDTOS = commentsRepository.selectByDiscussId(request
                .getDiscussId());
        return ResultBuilder.succTMulti(commentsDTOS);
    }

    @Override
    public TPageResult<CommentsDTO> queryPageMeComments(CommentsRequest request) {
        ServiceAssert.notBlank(request.getUserId(), Errors.Commons.REQUEST_PARAMETER_ERROR);
        return queryTPage(request);
    }

    @Override
    public TPageResult<CommentsDTO> queryPageToMeComments(CommentsRequest request) {
        ServiceAssert.notBlank(request.getToUserId(), Errors.Commons.REQUEST_PARAMETER_ERROR);
        return queryTPage(request);
    }

    private TPageResult<CommentsDTO> queryTPage(CommentsRequest request) {
        List<CommentsDTO> commentsDTOList = commentsRepository.queryByPage(request);
        int queryPageCount = commentsRepository.queryByCount(request);
        return ResultBuilder.succTPage(commentsDTOList, request.getPage(), request.getRows(),
                queryPageCount);
    }

    /**
     * 根据评论id删除评论 / 物理删除
     *
     * @param request 评论id 不能为空
     * @return {@link BaseResult} 执行结果
     */
    @Override
    public BaseResult deleteById(CommentsRequest request) {
        ServiceAssert.notNull(request.getId(), Errors.Commons.REQUEST_PARAMETER_ERROR);
        commentsRepository.delete(request.getId());
        return ResultBuilder.succ(BaseResult.class);
    }

    /**
     * 批量删除评论
     *
     * @param request 评论id[ids]集合不能为空
     * @return {@link BaseResult} 执行结果
     */
    @Override
    public BaseResult batchDeleteByIds(CommentsIdsRequest request) {
        ServiceAssert.notNull(request, Errors.Commons.REQUEST_PARAMETER_ERROR);
        ServiceAssert.isTrue(!isEmpty(request.getIds()), Errors.Commons.REQUEST_PARAMETER_ERROR);
        request.getIds().forEach(item -> commentsRepository.delete(item));
        return ResultBuilder.succ(BaseResult.class);
    }

    /**
     * 用户对评论点赞
     *
     * @param request 评论id  不能为空
     * @return {@link BaseResult} 执行结果
     */
    @Override
    public BaseResult onFabulous(CommentsFabulousRequest request) {
        ServiceAssert.notNull(request, Errors.Commons.REQUEST_PARAMETER_ERROR);
        ServiceAssert.notNull(request.getId(), Errors.Commons.REQUEST_PARAMETER_ERROR);
        CommentsDTO commentsDTO = commentsRepository.queryById(request.getId());
        if (commentsDTO == null) {
            LOGGER.error("评论信息不存在,评论id:{}", request.getId());
            return ResultBuilder.failTSingle(Errors.Commons.SYSTEM_ERROR);
        }
        if (StringUtil.equals(request.getUserId(), commentsDTO.getUserId())) {
            LOGGER.error("发布评论的用户id不能和点赞的用户id一样");
            return ResultBuilder.failTSingle(Errors.Commons.SYSTEM_ERROR);
        }
        commentsRepository.modifyAddFabulousCount(request.getId());
        return ResultBuilder.succ(BaseResult.class);
    }
}
